export function getBasename(): string {
  let path = process.env.PUBLIC_URL;

  if (!path) {
    return "";
  }

  if (path[0] !== "/") {
    path = "/" + path;
  }
  if (path[path.length - 1] === "/") {
    path = path.substring(0, path.length - 1);
  }
  return path;
}

export const BASENAME = getBasename();

export function getApiUrl(uri: string): string {
  return `${window.location.protocol}//${window.location.host}${BASENAME}/../api${uri}`;
}

const AuthKey = "ipset-manager::authkey";

export function writeAuth(
  username: string,
  password: string,
  permanent?: boolean
): boolean {
  try {
    const base64 = window.btoa(`${username}:${password}`);
    const auth = "Basic " + base64;

    sessionStorage.setItem(AuthKey, auth);
    if (permanent) {
      localStorage.setItem(AuthKey, auth);
    } else {
      localStorage.setItem(AuthKey, "");
    }
    return true;
  } catch (e) {
    console.log(e);
  }
  return false;
}

export function getAuth(): string | null {
  let auth = sessionStorage.getItem(AuthKey);
  if (!auth) {
    auth = localStorage.getItem(AuthKey);
  }
  return auth;
}

export function clearAuth(): boolean {
  sessionStorage.setItem(AuthKey, "");
  localStorage.setItem(AuthKey, "");
  return true;
}

export function handleUnauthorized(url: string) {}
